import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getUserInfo } from '@/api/user'
import type { LoginResult, UserInfo } from '@/types/user'
import type { PersistenceOptions } from 'pinia-plugin-persistedstate'
import { resetRouter } from '@/router'

export const useUserStore = defineStore('user', () => {
  // state
  const token = ref('')
  const userInfo = ref<UserInfo | null>(null)
  const permissions = ref<string[]>([])
  const roles = ref<string[]>([])

  // actions
  function setToken(newToken: string) {
    if (!newToken) {
        console.error('设置 token 失败：token 为空')
        return
      }
    token.value = newToken
    console.log('token 已设置:', newToken)
  }

  function setUserInfo(info: LoginResult) {
      if (!info) {
        console.error('设置用户信息失败：info 为空')
        return
      }

    // 直接使用后端返回的权限和角色
    permissions.value = info.permissions || []
    roles.value = info.roles || []
      
      // 更新用户基本信息
    userInfo.value = {
        id: info.userId,
        username: info.username,
        phone: null,
        balance: 0,
        status: 1,
        createTime: '',
        updateTime: ''
      }

    console.log('用户信息已设置:', userInfo.value)
    console.log('用户权限:', permissions.value)
    console.log('用户角色:', roles.value)
  }

  async function getUserInfoAction(): Promise<UserInfo> {
      try {
      if (!token.value) throw new Error('未登录')

        const response = await getUserInfo()
      console.log('获取用户信息响应:', response)

        if (!response || !response.data) {
          throw new Error('用户信息为空')
        }

        const userData = response.data

        if (!userData.id) throw new Error('用户信息缺失 id')

        // 更新用户基本信息
      userInfo.value = userData

      console.log('用户信息已更新:', userInfo.value)
      return userInfo.value
      } catch (error: any) {
      console.error('获取用户信息失败:', error)
      clearUserData()
        throw error
      }
  }

  function clearUserData() {
    token.value = ''
    userInfo.value = null
    permissions.value = []
    roles.value = []
      sessionStorage.clear()
    console.log('已登出，状态已清空')
    }

  // 退出登录
  function logout() {
    clearUserData()
    resetRouter()
  }

  return {
    // state
    token,
    userInfo,
    permissions,
    roles,
    // actions
    setToken,
    setUserInfo,
    getUserInfo: getUserInfoAction,
    clearUserData,
    logout
  }
}, {
  persist: {
    storage: sessionStorage,
    paths: ['token', 'permissions', 'roles', 'userInfo'],
    key: 'user-store'
  } as PersistenceOptions
})
